package xiaohuo.fancyring.util

import eos.moe.dragoncore.api.SlotAPI
import github.saukiya.sxattribute.SXAttribute
import org.bukkit.attribute.Attribute
import org.bukkit.entity.Player
import org.serverct.ersha.api.AttributeAPI
import taboolib.platform.util.isNotAir
import taboolib.platform.util.sendLang
import xiaohuo.fancyring.FancyRing
import xiaohuo.fancyring.config.ConfigManager
import xiaohuo.fancyring.data.RunningRealBody
import java.util.*

val realBodyMap = hashMapOf<UUID, RunningRealBody>()

fun Player.showRealBody() {
    if (uniqueId in realBodyMap) {
        closeRealBody()
    } else {
        val item = SlotAPI.getCacheSlotItem(this, ConfigManager.realBodySlot)
        if (item.isNotAir()) {
            item.getRealBody()?.let { it ->
                val latest = getCoolDown("RealBody", it.coolDown)
                if (latest > 0) {
                    sendLang("InCoolDown", latest)
                    return
                }
                if (it.handleCost(this)) {
                    realBodyMap[uniqueId] = RunningRealBody(this, it).also {
                        getNearbyEntities(64.0, 64.0, 64.0).filterIsInstance<Player>().forEach { player ->
                            it.showToPlayer(player)
                        }
                        it.showToPlayer(this)
                    }
                    setCoolDown("RealBody")
                    updateStats(FancyRing::class.java, it.stats)
                } else {
                    sendLang("RealBodyFail", it.costVault, getHealthPercent(it.costHealth))
                }
            }
        }
    }
}

fun UUID.getRunningRealBody(): RunningRealBody? {
    return realBodyMap[this]
}

fun Player.closeRealBody() {
    realBodyMap[uniqueId]?.closeShow()
    realBodyMap -= uniqueId
}

fun Player.getHealthPercent(percent: Double): Double {
    return getAttribute(Attribute.GENERIC_MAX_HEALTH).baseValue * percent
}

fun Player.updateStats(key: Class<*>, stats: List<String>) {
    when (ConfigManager.rpgPlugin) {
        1 -> {
            SXAttribute.getApi().setEntityAPIData(key, uniqueId, SXAttribute.getApi().getLoreData(null, null, stats))
            SXAttribute.getApi().updateStats(this)
        }

        2 -> {
            AttributeAPI.addSourceAttribute(AttributeAPI.getAttrData(this), key.simpleName, stats)
        }

        3 -> {
            org.serverct.ersha.jd.AttributeAPI.addAttribute(this, key.simpleName, stats)
        }
    }
}

fun Player.takeStats(key: Class<*>) {
    when (ConfigManager.rpgPlugin) {
        1 -> {
            SXAttribute.getApi().removeEntityAPIData(key, uniqueId)
        }

        2 -> {
            AttributeAPI.takeSourceAttribute(AttributeAPI.getAttrData(this), key.simpleName)
        }

        3 -> {
            org.serverct.ersha.jd.AttributeAPI.deleteAttribute(this, key.simpleName)
        }
    }
}